<template>
    <div class="wise_man_list_container">
        <ZWSearch row-num="3" :option="searchOption" @search="search" @reset="reset" />
        <ZwTable
            ref="listTableRef"
            tab-h="initial"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()">
            <template #headerOperateLeft>
                <div class="remindBtn" @click="showReminderHandler">
                    <el-icon :size="14"> <Setting /> </el-icon>
                    过期提醒
                </div>
            </template>
            <template #headerOperate>
                <span v-auth="'ADD_WISEMAN'">
                    <span class="addManCount">（最多可添加 {{ Data.restCount }} 个）</span>
                    <el-button type="primary" :disabled="!Data.restCount" @click="addHandler">添加达人</el-button>
                </span>
            </template>
        </ZwTable>
        <el-dialog
            v-model="dialog.showCreate"
            class="add-dialog"
            width="30%"
            destroy-on-close
            :close-on-click-modal="false"
            title="添加达人">
            <el-form ref="createFormRef" :rules="rules" :model="dialog" label-width="auto">
                <el-form-item label="来源渠道：">
                    <el-radio-group v-model="dialog.daren_channel_id">
                        <el-radio :label="21">抖音达人</el-radio>
                        <el-radio :label="22">快手达人</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="达人名称：" prop="daren_name">
                    <el-input
                        v-model.trim="dialog.daren_name"
                        show-word-limit
                        maxlength="20"
                        placeholder="请填写达人名称"
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="达人账号：" prop="daren_account">
                    <el-input
                        v-model.trim="dialog.daren_account"
                        show-word-limit
                        maxlength="50"
                        placeholder="请填写达人账号"
                        autocomplete="off" />
                    <div v-if="dialog.daren_channel_id == 22" class="tip-alert" @click="toCheck">
                        如何查看快手达人ID？
                    </div>
                </el-form-item>
                <el-form-item label="" prop="agreement" style="margin-bottom: 0">
                    <div class="vertical">
                        <el-checkbox v-model="dialog.agreement"> 同意 </el-checkbox>
                        <div class="link" @click="openPrivacyHandler">《隐私声明》</div>
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <div>
                        <div v-show="dialog.daren_channel_id == 22">
                            请先订购<span class="dialog-alert" @click="jumpTokeyida">客易达应用</span>，若已订购请忽略
                        </div>
                    </div>
                    <el-button
                        type="primary"
                        :disabled="!(dialog.agreement && dialog.daren_name && dialog.daren_account)"
                        @click="onAuthComfirmHandler">
                        立即授权
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 联系客服弹框 -->
        <el-dialog v-model="wechatDialogVisible" title="联系客服" width="25%" align-center>
            <div class="transform-wechat-body">
                <el-image src="//static.scrm.keyid.cn/assets/images/global/service.png"></el-image>
                <p style="text-align: center">请使用微信或企业微信扫码联系我们</p>
                <p style="text-align: center">
                    <el-icon><Clock /></el-icon>工作日：9:00~20:00
                </p>
            </div>
        </el-dialog>
        <!-- 提示购买客易达应用弹框 -->
        <el-dialog v-model="buyDialogVisible" title="提示" width="25%" align-center>
            <div class="transform-buy-body">请先购买客易达应用，再授权达人账号。</div>
            <template #footer>
                <div class="dialog-buy-alert">
                    <el-button type="primary" @click="buyDialogVisible = false"> 好的 </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 快手达人授权弹框 -->
        <el-dialog
            v-model="kuaishouDialogVisible"
            class="dialog-content-head"
            title="快手达人授权"
            width="35%"
            align-center
            :before-close="closeHandler">
            <div v-loading="loading" class="transform-wechat-body">
                <div class="transform-tips">请打开快手APP使用扫一扫功能进行授权</div>
                <div class="transform-tips">
                    若授权成功，请
                    <span class="alert-jump" @click="updataTable">点击此处刷新</span>
                    达人列表
                </div>
                <el-image :src="ksCodeUrl"></el-image>
            </div>
        </el-dialog>
        <ZWDeletdialog ref="buydialogRef" @submit="onDeleteSubmit" />
        <!-- 过期提醒设置弹窗 -->
        <remindDialog ref="remindDialogRef"></remindDialog>
        <!-- 删除弹框 -->
        <ZWDeletdialog ref="DeletdialogRef" @submit="onDeleteSubmit" />
        <!-- 授权失败 -->
        <ZWDialog :app-dialog="appDialog">
            <div class="dialog_tip_container">
                <div>达人授权失败</div>
                <div>请稍后再试</div>
            </div>
        </ZWDialog>
    </div>
</template>

<script setup lang="tsx">
import { reactive, ref, onMounted, computed } from 'vue';
import { ElMessage, ElButton, ElPopper } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import ZWSearch from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table1.0/Table';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import ZWDialog from '@/components/Dialog.vue';
import ZWDepart from '@/components/zw/depart/Depart';
import remindDialog from './remindDialog.vue';
import storage from '@/utils/storage';
import { useRoute } from 'vue-router';

const ksCodeUrl = ref('https://img-scrm-dev.keyid.cn/kuaishou-qrcode_100_200_1953332880.png'); //快手授权二维码
const router = useRoute();
import {
    getWiseManList,
    getWiseManRestCount,
    deleteWiseMan,
    createWiseMan,
    authKuaishouWiseMan,
    authWiseMan,
    getCreateWiseManResult
} from '@/api/ecommerce/wiseManList';
import lodash from 'lodash';
import { type } from '@/components/zw/utils';

const loading = ref(false);
const Data = reactive({
    restCount: 0,
    id: ''
});
const wechatDialogVisible = ref(false);
const searchOption = computed(() => {
    return [
        {
            label: '达人信息',
            name: 'daren_name',
            type: 'input',
            value: '',
            placeholder: '请输入达人名称/账号'
        },
        {
            label: '来源渠道',
            name: 'daren_channel_id',
            value: '0',
            type: 'select',
            placeholder: '全部',
            optionList: [
                { label: '全部', value: '0' },
                { label: '抖音达人', value: '21' },
                { label: '快手达人', value: '22' }
            ]
        },
        {
            label: '达人状态',
            name: 'auth_status',
            value: '0',
            type: 'select',
            placeholder: '全部',
            optionList: [
                { label: '全部', value: '0' },
                { label: '未授权', value: 1 },
                { label: '正常', value: 2 },
                { label: '已过期', value: 3 }
            ]
        },
        {
            label: '创建时间',
            name: 'time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        }
    ];
});
const currentParams = ref<any>(null);

const search = (data: any): void => {
    if (data.auth_status) {
        data.auth_status = data.auth_status == '0' ? '' : [data.auth_status];
    }
    state.searchParams = data;
    currentParams.value = data;
};
const reset = (): void => {
    state.searchParams = lodash.cloneDeep(defaultParams);
    currentParams.value = null;
};

type defaultParamsType = {
    daren_channel_id: number | string;
    auth_status: number | string;
};

const defaultParams: defaultParamsType = {
    daren_channel_id: 0,
    auth_status: ''
};

type stateType = {
    searchParams: any;
    deleteId: number | string;
};

const tableOption = [
    {
        prop: 'channel_name',
        label: '渠道',
        render({ row }: any) {
            return row?.channel_name || '--';
        }
    },
    {
        prop: 'daren_name',
        label: '达人信息',
        render({ row }: any) {
            return (
                <>
                    <div>{row?.daren_name}</div>
                    <div>{row?.daren_account}</div>
                </>
            );
        }
    },
    {
        prop: 'auth_status',
        label: '达人状态',
        render({ row }: any) {
            return ['', '未授权', '正常', '已过期'][row?.auth_status] || '--';
        }
    },
    {
        prop: 'effect_day',
        label: '剩余有效期',
        render({ row }: any) {
            return row?.auth_status > 1 ? (row.effect_day || 0) + '天' : '--';
        }
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 180,
        render({ row }: any) {
            return row?.created_at || '--';
        }
    },
    {
        prop: 'operate',
        label: '操作',
        width: 150,
        isOperate: true,
        option: [
            {
                name: '立即授权',
                authCode: 'ADD_WISEMAN',
                click: (row: any) => onAuthHandler(row, 1),
                isRender: ({ row }: any) => row.auth_status == 1
            },
            {
                name: '重新授权',
                authCode: 'ADD_WISEMAN',
                click: (row: any) => onAuthHandler(row, 2),
                isRender: ({ row }: any) => row.auth_status == 3 || row.auth_status == 2
            },
            {
                name: '删除',
                authCode: 'DEL_WISEMAN',
                click: (row: any) => deleteHandler(row)
            }
        ]
    }
];

const fetchApi = (): any => {
    return new Promise((resolve: any): any => {
        resolve([{}, getWiseManList]);
    });
};

const state = reactive<stateType>({
    searchParams: lodash.cloneDeep(defaultParams),
    deleteId: ''
});

const dialog = reactive({
    showRemind: false,
    showCreate: false,
    daren_account: '',
    daren_name: '',
    agreement: false,
    daren_channel_id: 21 //渠道，21抖音达人 22快手达人
});
const createFormRef = ref<FormInstance>();

const rules = reactive<FormRules>({
    daren_account: [
        {
            required: true,
            message: '达人名称不能为空',
            trigger: 'blur'
        }
    ],
    daren_name: [
        {
            required: true,
            message: '达人账号不能为空',
            trigger: 'blur'
        }
    ]
});

// 点击添加达人按钮
const addHandler = (): void => {
    dialog.daren_channel_id = 21;
    dialog.daren_name = '';
    dialog.daren_account = '';
    dialog.agreement = false;
    dialog.showCreate = true;
};
const DeletdialogRef = ref();
// 列表点击删除
const deleteHandler = (row: any) => {
    DeletdialogRef.value.appDialog.title = '提示';
    DeletdialogRef.value.content =
        '<div style="font-weight:600; font-size:15px">确定删除吗？</div><div>删除后，订单不再同步，且不支持转换。</div>';
    Data.id = row.id;
    DeletdialogRef.value.appDialog.visible = true;
};
// 确认删除
const onDeleteSubmit = async () => {
    await deleteWiseMan({ id: Data.id });
    queryWiseManRestCount();
    state.searchParams = { ...lodash.cloneDeep(defaultParams), ...currentParams.value };
};

// 列表：立即授权 || 重新授权
// "id": 达人id "type": 1 //1-立即授权 2-重新授权
const onAuthHandler = async (val: any, type: number) => {
    if (val.daren_channel_id == 22) {
        loading.value = true;
        // 快手达人授权
        const data = await authKuaishouWiseMan({ id: val.id, type: type });
        ksCodeUrl.value = data.url;
        loading.value = false;
        kuaishouDialogVisible.value = true;
    } else {
        // 抖音达人授权
        const data = await authWiseMan({ id: val.id, type: type });
        storage.set('jumpWiseManAuth', 1);
        location.href = data;
    }
};

const remindDialogRef = ref();
// 点击过期提醒
const showReminderHandler = (): void => {
    remindDialogRef.value.openDialog();
};

// 打开隐私声明
const openPrivacyHandler = (): void => {
    window.open('https://static.scrm.keyid.cn/assets/files/privacy-statement.pdf');
};

// 添加达人立即授权
const onAuthComfirmHandler = () => {
    if (!createFormRef.value) return;

    createFormRef.value.validate(async (valid: boolean) => {
        if (valid) {
            // 2.不存在抖音跳到抖音授权页
            const data = await createWiseMan({
                daren_name: dialog.daren_name, //达人信息
                daren_account: dialog.daren_account, //达人账号
                daren_channel_id: dialog.daren_channel_id
            });
            // 达人授权
            if (data.code == 0 && dialog.daren_channel_id == 21) {
                // 抖音达人授权,跳转到授权页
                storage.set('jumpWiseManAuth', 1);
                location.href = data.data;
            } else if (data.code == 0 && dialog.daren_channel_id == 22) {
                //快手授权，弹出快手授权二维码
                ksCodeUrl.value = data.data.url;
                dialog.showCreate = false;
                kuaishouDialogVisible.value = true;
            } else if (data.code == 72007) {
                //抖音达人的授权数是否大于20，大于20，弹出联系企业微信客服
                wechatDialogVisible.value = true;
            } else if (data.code == 72004) {
                // 未购买客易达应用，弹出未购买弹框
                buyDialogVisible.value = true;
            } else {
                ElMessage.error(data.msg);
            }
        }
    });
};

// 获取可添加达人数
const queryWiseManRestCount = async () => {
    const data: any = await getWiseManRestCount('');
    Data.restCount = data?.daren_num || 0;
};

// 提示弹窗
const appDialog = reactive({
    visible: false,
    title: '提示',
    width: '400px',
    submit: () => {
        appDialog.visible = false;
    },
    submitText: '确定'
});
// 授权回调
const queryWiseManAuthResult = async () => {
    storage.remove('jumpWiseManAuth');
    try {
        await getCreateWiseManResult(router.query);
        ElMessage.success('授权成功');
    } catch (e) {
        appDialog.visible = true;
    }
};

onMounted(() => {
    if (storage.get('jumpWiseManAuth') && router.query.session) {
        queryWiseManAuthResult();
    }
    queryWiseManRestCount();
});
const listTableRef = ref();
const buyDialogVisible = ref(false);
const kuaishouDialogVisible = ref(false);
const updataTable = () => {
    queryWiseManRestCount();
    kuaishouDialogVisible.value = false;
    listTableRef.value.reload();
};
const closeHandler = () => {
    updataTable();
};
// 跳转客易达应用
const jumpTokeyida = () => {
    const ids = {
        dev: 20711841337205,
        test: 20711841337205,
        uat: 20711804664205,
        prod: 20711804664205
    };
    window.open(`https://fuwu.kwaixiaodian.com/detail?id=${ids[import.meta.env.MODE] || 20711841337205}`);
};
/**跳转到引导页*/
const toCheck = () => {
    window.open('/kuaishou-id-guide');
};
</script>

<style lang="scss" scoped>
.wise_man_list_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-pagination) {
            margin-top: 16px;
        }

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }

    .vertical {
        display: flex;
        align-items: center;
    }

    .tip-alert {
        font-size: 14px;
        font-family: PingFangSC-Regular, 'PingFang SC';
        font-weight: 400;
        color: #ff6b00;
        cursor: pointer;
    }

    .transform-buy-body {
        padding: 16px;
        text-align: center;
    }

    :deep(.dialog-content-head .el-dialog__header .el-dialog__title) {
        font-weight: 500;
        color: #33302d;
    }

    .transform-wechat-body {
        display: flex;
        align-items: center;
        flex-direction: column;
        justify-content: center;
        margin-top: 20px;

        .transform-tips {
            text-align: center;
            font-size: 14px;
            font-family: PingFangSC-Regular, 'PingFang SC';
            font-weight: 400;
            color: #33302d;
            line-height: 20px;

            .alert-jump {
                cursor: pointer;
                color: #ff6b00;
            }
        }

        p {
            margin: 20px 0;
            color: #333;

            &:last-of-type {
                margin: 0;
                margin-bottom: 40px;
                display: flex;
                align-items: center;
                color: #969696;

                i {
                    margin-right: 4px;
                }
            }
        }
    }

    :deep(.add-dialog .el-dialog__body) {
        padding: 24px !important;
    }

    :deep(.add-dialog .el-dialog__footer) {
        padding: 13px 24px;
    }

    .dialog-buy-alert {
        display: flex;
        justify-content: flex-end;
    }

    .dialog-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 14px;
        font-family: PingFangSC-Regular, 'PingFang SC';
        font-weight: 400;
        color: #33302d;
        line-height: 16px;

        .dialog-alert {
            cursor: pointer;
            color: #ff6b00;
        }
    }

    .remindBtn {
        height: 32px;
        line-height: 32px;
        text-align: center;
        background: #fff;
        border-radius: 4px;
        font-size: 14px;
        font-weight: 400;
        color: #ff6b00;
        border: 1px solid #ff6b00;
        display: flex;
        align-items: center;
        justify-content: space-around;
        padding: 0 12px;
        cursor: pointer;
    }

    .addManCount {
        margin: auto;
        margin-right: 8px;
        font-size: 12px;
        font-weight: 400;
        color: #585858;
    }

    .link {
        color: #ff6b00;
        cursor: pointer;
    }

    .dialog_tip_container {
        height: 100px;
        line-height: 25px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;

        :nth-child(1) {
            font-weight: 600;
            font-size: 15px;
        }
    }
}
</style>
